<template>
  <Dialog :appDialog="appDialog">
    <el-form ref="formRef" :model="groupData" label-width="110px" class="demo_dynamic">
      <el-form-item
        prop="group_title"
        label="标签组名称："
        :rules="[
          {
            required: true,
            message: '标签组名称不能为空',
            trigger: 'blur'
          }
        ]"
        size="small"
      >
        <el-input class="group_data_name" v-model="groupData.group_title" maxlength="15" placeholder="请输入标签组名" show-word-limit></el-input>
      </el-form-item>
      <el-form-item
        class="tag_group"
        prop="group_type"
        label="标签组类别："
        :rules="[
          {
            required: true,
            message: '标签组类别不能为空',
            trigger: 'blur'
          }
        ]"
        size="small"
      >
        <el-select style="width: 300px" allow-create default-first-option filterable clearable v-model="groupData.group_type" placeholder="全部" @change="selectGroupType">
          <el-option v-for="item in props.allTags" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        class="tag_group"
        prop="add_tags"
        label="标签："
        :rules="
          !isEdit
            ? [
                {
                  required: true,
                  message: '标签不能为空',
                  trigger: 'blur'
                }
              ]
            : []
        "
      >
        <span class="zw-el-tags">
          <el-tag v-for="k in tags" :key="k.name" closable @close="handleClose(k)">
            {{ k.name }}
          </el-tag>
        </span>
        <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" class="create_label_input" size="small" maxlength="15" @keyup.enter="handleInputConfirm" @blur="handleInputConfirm"> </el-input>
        <el-button v-else plan class="button-new-tag ml-1" size="small" @click="createLabel">新建标签</el-button>
      </el-form-item>
    </el-form>
  </Dialog>
</template>
<script setup lang="ts">
  import { ref, reactive, nextTick, watch } from 'vue'
  import Dialog from './Dialog.vue'
  import { ElInput, ElForm, ElMessage } from 'element-plus'
  import { editTagGroup ,addTags} from '@/api/customerLabel'
  import { getSetionId,IsNotEmpty } from '@/utils/utils'
  import bus from '@/utils/bus'
  const InputRef = ref<InstanceType<typeof ElInput>>()
  const formRef = ref<InstanceType<typeof ElForm>>()
  const props = defineProps(['allTags'])
  const emit = defineEmits(['submit'])
  const inputValue = ref('')
  const inputVisible = ref(false)
  const isEdit = ref(false)
  interface Tag {
    id?: number
    name: string
  }
  interface TagGroup extends Tag {
    tags: Tag[]
  }
  // 新建分组
  const groupData = reactive({
    group_title: '',
    group_type: '',
    add_tags: [],
    update_tags: [],
  })
  const cancelHandel = () => {
    appDialog.value.visible = false
    formRef.value.resetFields()
    isEdit.value = false
    groupData.group_title = ''
    groupData.group_type = ''
    tags.value = []
    groupData.add_tags = []
    groupData.update_tags = []
    emit('submit')
  }
  const selectGroupType = (val:any)=>{
    console.log(val,111)
  }
  // 保存标签
  const submitHandel = () => {
    formRef.value.validate(async (valid: any) => {
      if (valid) {
        const addTag = tags.value.filter((item:any)=>!item.id)
        groupData.add_tags = getSetionId('name',addTag);
        let params = {
          group_title:groupData.group_title,
          update_tags:groupData.update_tags,
          group_id:groupData.group_id,
          tags:groupData.add_tags,
          // group_type:{
          //   id:groupData.group_type,
          //   name:props.allTags.find((item:any)=>item.id==groupData.group_type)?.name
          // }
        }
        const sss = props.allTags.find((item:any)=>item.id==groupData.group_type)?.name
        if(!sss){
          params.group_type={
            name : groupData.group_type
          }
        }else{
          params.group_type = {
            id:groupData.group_type,
            name:props.allTags.find((item:any)=>item.id==groupData.group_type)?.name
          }
        } 
        if(!isEdit.value) delete params.group_id
        // let groupDataTwo = JSON.parse(JSON.stringify(groupData))
        // let index = props.allTags.findIndex((it: any) => {
        //   return it.id == groupDataTwo.group_type
        // })
        // let groupType: any = {}
        // if (index > -1) {
        //   groupType = { id: groupDataTwo.group_type, name: props.allTags[index].name }
        // } else {
        //   groupType.name = groupDataTwo.group_type
        // }
        // groupDataTwo.group_type = groupType

        if (!tags.value.length) {
          ElMessage.error('请填写标签')
          return
        }
        console.log(params,'===params')
        try {
          isEdit.value ? await editTagGroup(params) : await addTags(params)
          ElMessage.success(`${isEdit.value ? '编辑' : '新建'}标签成功`)
          cancelHandel()
          
        } catch (e) {
          console.log(e)
        }
      }
    })
  }

  const appDialog = ref({
    visible: false,
    title: `新建标签组`,
    width: '700px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '保存'
  })

  const tags = ref([])
  const handleClose = (tag: any) => {
    if(tag?.id){
      groupData.update_tags.push(tag?.id)
    }
    tags.value = tags.value.filter((item: any) => item.name !== tag.name)
  }
  const createLabel = () => {
    inputVisible.value = true
    nextTick(() => {
      InputRef.value!.input!.focus()
    })
  }
  const handleInputConfirm = () => {
    if (tags.value.length > 100) {
      ElMessage.warning('标签最多创建100个')
      return
    }
    if (inputValue.value) {
      if (tags.value.includes(inputValue.value)) {
        ElMessage.warning('新建标签名不能重复')
        return
      }
      tags.value.push({ name: inputValue.value })
      groupData.add_tags.push(inputValue.value)
    }
    inputVisible.value = false
    inputValue.value = ''
  }
  // 数据回显
  const echo = (data: any) => {
    console.log(data,333)
    isEdit.value = true
    groupData.group_id = data.group_id
    groupData.group_title = data.group_name
    groupData.group_type = data?.group_type_id
    // groupData.group_type_name = data.group_type_value
    tags.value = data.tags
  }
  defineExpose({
    appDialog,
    groupData,
    isEdit,
    echo
  })
</script>
<style lang="scss" scoped>
  .demo_dynamic {
    margin-top: 14px;
    .group_data_name {
      width: 300px;
    }
    .create_label_input {
      width: 140px;
    }
    .mr15 {
      margin-right: 15px;
    }
    .tag_group {
      margin: 20px 0;
    }
  }
  .zw-el-tags {
    margin-right: 6px;
  }
</style>
